#!/usr/bin/env python
# -*- coding:utf-8 -*-

from pyquery import PyQuery

from base.gsxt_base_worker import GsxtBaseWorker
from common.global_field import Model


class GsxtTianJinWorker(GsxtBaseWorker):
    def __init__(self, **kwargs):
        GsxtBaseWorker.__init__(self, **kwargs)

    # 需要存入无搜索结果
    def get_search_result_html(self, keyword, session):
        url_list = []
        url = 'http://www.tjcredit.gov.cn/gsxt/platform/searchResult?searchName={0}&searchType=FUZZY_SEARCH'.format(
            keyword)
        content = self.task_request(session.get, url)
        jq = PyQuery(content.text, parser='html')
        item_list = jq.find('dl').find('a')
        for i in range(0, len(item_list)):
            href = item_list.eq(i).attr('onclick')
            if href is None or href == '':
                continue
            gsdjlx = href.split('\'')[3]
            entId = href.split('\'')[1]
            url = 'http://www.tjcredit.gov.cn/gsxt/platform/viewInfo.json?gsdjlx={0}&entId={1}&wbjCode=scjgw&type=reginfo'.format(
                gsdjlx, entId)
            url_list.append({'href': url})
        return url_list, self.SEARCH_SUCCESS if len(url_list) > 0 else self.SEARCH_NOTHING_FIND

    def __get_company_name(self, text):
        try:
            result = PyQuery(text, parser='html').find('table[class="info-table"]').eq(0).find('tr')

            for i in range(0, len(result)):
                if '注册号' in result.eq(i).text():
                    name = result.eq(i).find('td').eq(3).text()
                    return name
        except Exception as e:
            self.log.exception(e)
            return None

        return None

    # 基本信息
    def get_base_info(self, session, url):
        # 获取基础信息
        url = url
        base_info = self.task_request(session.get, url)
        if base_info is None:
            self.log.error('获取基础信息页面失败...')
            return None, None
        return url, base_info.text

    # 出资信息
    def get_shareholder_info(self, session, url_list, data):
        try:
            for url in url_list:
                r = self.task_request(session.get, url)
                if r is None:
                    return
                self.append_model(data, Model.shareholder_info, url, r.text)
            return
        except Exception as e:
            self.log.exception(e)

    # 主要人员
    def get_key_person_info(self, session, param_dict, data):
        gsdjlx = param_dict['gsdjlx']
        entId = param_dict['entId']
        wbjCode = param_dict['wbjCode']
        url = 'http://www.tjcredit.gov.cn/gsxt/platform/viewInfo.json?gsdjlx={gsdjlx}&entId={entId}&wbjCode={wbjCode}&type=bakrecord'.format(
            entId=entId, wbjCode=wbjCode, gsdjlx=gsdjlx)
        r = self.task_request(session.get, url)
        if r is None:
            return
        self.append_model(data, Model.key_person_info, url, r.text)

    # def get_annual_info(self, session, text, data):
    #     # 暂时不处理 跟解析沟通一下
    #     for year, url in self.get_year_info_list(text):
    #         r = self.task_request(session.get, url)
    #         if r is None:
    #             continue
    #         self.append_model(data, Model.annual_info, url, r.text, year=year, classify=Model.type_detail)

    def parse_param(self, href):
        # 'http://www.tjcredit.gov.cn/gsxt/platform/viewInfo.json?gsdjlx=1&entId=c01aa17e53ee8a281e09d1d26022b992&wbjCode=scjgw&type=reginfo'
        param_dict = {}
        try:
            sub_url_list = href.split('?')
            sub_url = sub_url_list[1]
            sub_list = sub_url.split('&')
            if len(sub_list) < 3:
                return None
            for item in sub_list:
                item_list = item.split('=')
                if len(item_list) < 2:
                    continue
                param_dict[item_list[0]] = item_list[1]
            if 'entId' not in param_dict:
                return None
        except Exception as e:
            self.log.exception(e)
            return None

        return param_dict

    def get_detail_html_list(self, seed, session, param_list):
        # 保存企业名称
        data_list = []
        rank = 0
        for item in param_list:
            try:
                href = item.get('href', None)
                if href is None:
                    self.log.error('参数存储异常: item = {item}'.format(item=item))
                    continue
                # 基本信息 股东信息 变更信息
                url, base_text = self.get_base_info(session, href)
                if base_text is None:
                    continue
                # 获得公司名称
                company_name = self.__get_company_name(base_text)
                if company_name is None or company_name == '':
                    self.log.error('公司名称解析失败..param_dict = {param_dict} {text}'.format(
                        text=base_text, param_dict=href))
                    continue
                # 建立数据模型
                rank += 1
                param_dict = self.parse_param(href)
                data = self.get_model(company_name, rank, seed, self.province)
                # 存储数据
                self.append_model(data, Model.base_info, url, base_text)
                if '出资人及出资信息' in base_text:
                    table = PyQuery(base_text, parser='html').find('table[class="info-table"]').eq(1).find('a')
                    url_list = []
                    for i in range(0, len(table)):
                        gsdjlx = table.eq(i).attr('onclick').split('\',\'')[2]
                        proId = table.eq(i).attr('onclick').split('\'')[1].split('\',\'')[0]
                        wbjCode = 'scjgw'
                        url = 'http://www.tjcredit.gov.cn/gsxt/platform/viewDetailInfo.json?gsdjlx={gsdjlx}&wbjCode={wbjCode}&type=reginfo&tableName=T_GS_REGINFO_INVINFO&proId={proId}'.format(
                            gsdjlx=gsdjlx, proId=proId, wbjCode=wbjCode)
                        url_list.append(url)
                    # 出资信息
                    self.get_shareholder_info(session, url_list, data)

                # 主要人员信息 分支机构
                self.get_key_person_info(session, param_dict, data)

                # 6.5W家年报暂时满足要求 可暂缓
                # self.get_annual_info(session, base_text, data)

                data_list.append(data)
            except Exception as e:
                self.log.exception(e)
        self.target_db.insert_batch_data(self.target_table, data_list)
        return len(data_list)

# if __name__ == '__main__':
#     zongju = GsxtTianJinWorker()
#     session = requests.session()
#     zongju.get_search_result_html('测试', session)
#     zongju.parse_param(
#         'http://www.tjcredit.gov.cn/gsxt/platform/viewInfo.json?gsdjlx=1&entId=c01aa17e53ee8a281e09d1d26022b992&wbjCode=scjgw&type=reginfo')
